import Mn from 'backbone.marionette';
import TaskLineCollectionView from './TaskLineCollectionView.js';
import TaskLineFormView from './TaskLineFormView.js';
import TaskLineModel from "../../../../models/TaskLineModel.js";
import TaskGroupTotalView from './TaskGroupTotalView.js';
import {
    formatAmount
} from '../../../../../math.js';
import {
    displayServerSuccess,
    displayServerError
} from '../../../../../backbone-tools.js';
import Validation from 'backbone-validation';
import Radio from 'backbone.radio';
import {
    strToFloat
} from 'math.js';

const template = require('./templates/TaskGroupView.mustache');

const TaskGroupView = Mn.View.extend({
    tagName: 'div',
    className: 'taskline-group row quotation_item border_left_block composite content_double_padding',
    template: template,
    regions: {
        errors: '.errors',
        lines: {
            el: '.lines',
            replaceElement: true
        },
        modalRegion: ".modalregion",
        subtotal: {
            el: '.subtotal',
            replaceElement: true
        }
    },
    ui: {
        btn_add: ".btn-add",
        up_button: 'button.up',
        down_button: 'button.down',
        edit_button: 'button.edit',
        delete_button: 'button.delete'
    },
    triggers: {
        'click @ui.up_button': 'order:up',
        'click @ui.down_button': 'order:down',
        'click @ui.edit_button': 'edit',
        'click @ui.delete_button': 'delete'
    },
    events: {
        "click @ui.btn_add": "onLineAdd"
    },
    childViewEvents: {
        'line:edit': 'onLineEdit',
        'line:delete': 'onLineDelete',
        'catalog:insert': 'onCatalogInsert',
        'destroy:modal': 'render',
    },
    initialize: function (options) {
        // Collection of task lines
        this.collection = this.model.lines;
        this.listenTo(this.collection, 'sync', this.render.bind(this));

        var channel = Radio.channel('facade');
        this.config = Radio.channel('config');
        this.user_prefs = Radio.channel('user_preferences');

        this.listenTo(channel, 'bind:validation', this.bindValidation);
        this.listenTo(channel, 'unbind:validation', this.unbindValidation);
        this.listenTo(this.model, 'validated:invalid', this.showErrors);
        this.listenTo(this.model, 'validated:valid', this.hideErrors.bind(this));
        this.compute_mode = this.config.request('get:options', 'compute_mode');
        this.is_ttc_mode = this.compute_mode == 'ttc';

        this.edit = this.getOption('edit');
        this.section = options['section'];
        this.useDate = this.section.hasOwnProperty('date');
    },
    isEmpty: function () {
        return this.model.lines.length === 0;
    },
    showErrors(model, errors) {
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.$el.removeClass('error');
    },
    bindValidation() {
        Validation.bind(this);
    },
    unbindValidation() {
        Validation.unbind(this);
    },
    showLines() {
        /*
         * Show lines if it's not done yet
         */
        if (!_.isNull(this.getChildView('lines'))) {
            this.showChildView(
                'lines',
                new TaskLineCollectionView({
                    collection: this.collection,
                    edit: this.edit,
                    is_ttc_mode: this.is_ttc_mode,
                    section: this.section
                })
            );
        }
    },
    onRender: function () {
        // Fix #4254 : Scroll après modification de ligne produit
        document.body.classList.remove('modal_open');
        if (!this.isEmpty()) {
            this.showLines();
        }
        let totalColspan = 5;
        if (this.useDate) {
            totalColspan += 1;
        }
        this.showChildView(
            'subtotal',
            new TaskGroupTotalView({
                collection: this.collection,
                colspan: totalColspan,
            })
        );
    },
    onLineEdit: function (childView) {
        this.showTaskLineForm(childView.model, "Modifier le produit", true);
    },
    onLineAdd: function () {
        var model = new TaskLineModel({
            task_id: this.model.get('id'),
            order: this.collection.getMaxOrder() + 1,
        });
        this.showTaskLineForm(model, "Ajouter un produit", false);
    },
    showTaskLineForm: function (model, title, edit) {
        var form = new TaskLineFormView({
            model: model,
            title: title,
            destCollection: this.collection,
            edit: edit,
            section: this.section,
        });
        this.showChildView('modalRegion', form);
    },
    onDeleteSuccess: function () {
        displayServerSuccess("Vos données ont bien été supprimées");
    },
    onDeleteError: function () {
        displayServerError("Une erreur a été rencontrée lors de la " +
            "suppression de cet élément");
    },
    onLineDelete: function (childView) {
        var result = window.confirm("Êtes-vous sûr de vouloir supprimer ce produit ?");
        if (result) {
            childView.model.destroy({
                success: this.onDeleteSuccess,
                error: this.onDeleteError
            });
        }
    },
    onCatalogInsert: function (sale_products) {
        this.collection.load_from_catalog(sale_products);
        this.getChildView('modalRegion').triggerMethod('modal:close')
    },
    onChildviewDestroyModal: function () {
        this.getRegion('modalRegion').empty();
    },
    templateContext: function () {
        let min_order = this.model.collection.getMinOrder();
        let max_order = this.model.collection.getMaxOrder();
        let order = this.model.get('order');
        return {
            no_title_no_description: (this.model.get('title') === '' && this.model.get('description') === ''),
            group_description: this.model.get('description').replace('<p>', '').replace('</p>', ''),
            not_is_empty: !this.isEmpty(),
            total_ht: this.user_prefs.request('formatAmount', this.model.ht(), false),
            is_not_first: order != min_order,
            is_not_last: order != max_order,
            is_ttc_mode: this.is_ttc_mode,
            edit: this.edit,
            can_delete: this.section['can_delete'],
            hasDate: this.useDate,
            can_add: this.section['can_add'] && this.edit
        }
    }
});
export default TaskGroupView;